/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.gzchengguo.cn
* 注意：
* 本软件为www.gzchengguo.cn开发研制，未经购买不得商用
* 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
* 一经发现盗用、分享等行为，将追究法律责任，后果自负
*/
package link.chengguo.orangemall.modules.category.rest;

import cn.hutool.core.util.StrUtil;
import link.chengguo.orangemall.api.OrangeException;
import link.chengguo.orangemall.constant.ShopConstants;
import link.chengguo.orangemall.logging.aop.log.Log;
import link.chengguo.orangemall.modules.aop.ForbidSubmit;
import link.chengguo.orangemall.modules.category.domain.OrangeStoreCategory;
import link.chengguo.orangemall.modules.category.service.OrangeStoreCategoryService;
import link.chengguo.orangemall.modules.category.service.dto.OrangeStoreCategoryDto;
import link.chengguo.orangemall.modules.category.service.dto.OrangeStoreCategoryQueryCriteria;
import link.chengguo.orangemall.modules.product.domain.OrangeStoreProduct;
import link.chengguo.orangemall.modules.product.service.OrangeStoreProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
* @author chengguo
* @date 2019-10-03
*/
@Api(tags = "商城:商品分类管理")
@RestController
@RequestMapping("api")
public class StoreCategoryController {


    private final OrangeStoreCategoryService orangeStoreCategoryService;
    private final OrangeStoreProductService orangeStoreProductService;


    public StoreCategoryController(OrangeStoreCategoryService orangeStoreCategoryService,
                                   OrangeStoreProductService orangeStoreProductService) {
        this.orangeStoreCategoryService = orangeStoreCategoryService;
        this.orangeStoreProductService = orangeStoreProductService;
    }

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/orangeStoreCategory/download")
    @PreAuthorize("@el.check('admin','ORANGESTORECATEGORY_SELECT')")
    public void download(HttpServletResponse response, OrangeStoreCategoryQueryCriteria criteria) throws IOException {
        orangeStoreCategoryService.download(orangeStoreCategoryService.queryAll(criteria), response);
    }


    @Log("查询商品分类")
    @ApiOperation(value = "查询商品分类")
    @GetMapping(value = "/orangeStoreCategory")
    @PreAuthorize("hasAnyRole('admin','ORANGESTORECATEGORY_ALL','ORANGESTORECATEGORY_SELECT')")
    public ResponseEntity getOrangeStoreCategorys(OrangeStoreCategoryQueryCriteria criteria, Pageable pageable){
        List<OrangeStoreCategoryDto> categoryDTOList = (List<OrangeStoreCategoryDto>) orangeStoreCategoryService.queryAll(criteria,pageable).get("content");
        return new ResponseEntity<>(orangeStoreCategoryService.buildTree(categoryDTOList),HttpStatus.OK);
    }

    @ForbidSubmit
    @Log("新增商品分类")
    @ApiOperation(value = "新增商品分类")
    @PostMapping(value = "/orangeStoreCategory")
    @CacheEvict(cacheNames = ShopConstants.ORANGEMALL_REDIS_INDEX_KEY,allEntries = true)
    @PreAuthorize("hasAnyRole('admin','ORANGESTORECATEGORY_ALL','ORANGESTORECATEGORY_CREATE')")
    public ResponseEntity create(@Validated @RequestBody OrangeStoreCategory resources){
        if(resources.getPid() != null && resources.getPid() > 0 && StrUtil.isBlank(resources.getPic())) {
            throw new OrangeException("子分类图片必传");
        }

        boolean checkResult = orangeStoreCategoryService.checkCategory(resources.getPid());
        if(!checkResult) {
            throw new OrangeException("分类最多能添加2级哦");
        }

        return new ResponseEntity<>(orangeStoreCategoryService.save(resources),HttpStatus.CREATED);
    }

    @ForbidSubmit
    @Log("修改商品分类")
    @ApiOperation(value = "修改商品分类")
    @CacheEvict(cacheNames = ShopConstants.ORANGEMALL_REDIS_INDEX_KEY,allEntries = true)
    @PutMapping(value = "/orangeStoreCategory")
    @PreAuthorize("hasAnyRole('admin','ORANGESTORECATEGORY_ALL','ORANGESTORECATEGORY_EDIT')")
    public ResponseEntity update(@Validated @RequestBody OrangeStoreCategory resources){
        if(resources.getPid() != null && resources.getPid() > 0 && StrUtil.isBlank(resources.getPic())) {
            throw new OrangeException("子分类图片必传");
        }

        if(resources.getId().equals(resources.getPid())){
            throw new OrangeException("自己不能选择自己哦");
        }

        boolean checkResult = orangeStoreCategoryService.checkCategory(resources.getPid());

        if(!checkResult) {
            throw new OrangeException("分类最多能添加2级哦");
        }

        orangeStoreCategoryService.saveOrUpdate(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @ForbidSubmit
    @Log("删除商品分类")
    @ApiOperation(value = "删除商品分类")
    @CacheEvict(cacheNames = ShopConstants.ORANGEMALL_REDIS_INDEX_KEY,allEntries = true)
    @DeleteMapping(value = "/orangeStoreCategory/{id}")
    @PreAuthorize("hasAnyRole('admin','ORANGESTORECATEGORY_ALL','ORANGESTORECATEGORY_DELETE')")
    public ResponseEntity delete(@PathVariable String id){
        String[] ids = id.split(",");
        for (String newId: ids) {
            this.delCheck(Integer.valueOf(newId));
            orangeStoreCategoryService.removeById(Integer.valueOf(newId));
        }
        return new ResponseEntity(HttpStatus.OK);
    }


    /**
     * 检测删除分类
     * @param id 分类id
     */
    private void delCheck(Integer id){
        int count = orangeStoreCategoryService.lambdaQuery()
                .eq(OrangeStoreCategory::getPid,id)
                .count();
        if(count > 0) {
            throw new OrangeException("请先删除子分类");
        }

        int countP = orangeStoreProductService.lambdaQuery()
                .eq(OrangeStoreProduct::getCateId,id)
                .count();

        if(countP > 0) {
            throw new OrangeException("当前分类下有商品不可删除");
        }
    }
}
